from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.html import format_html

User = get_user_model()

class CustomUserAdmin(UserAdmin):
    list_display = ('username', 'email', 'is_active', 'date_joined', 'last_login', 'order_count', 'user_status')
    list_filter = ('is_active', 'is_staff', 'date_joined')
    search_fields = ('username', 'email')
    ordering = ('-date_joined',)
    
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('个人信息', {'fields': ('email', 'first_name', 'last_name')}),
        ('权限', {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        ('重要日期', {'fields': ('last_login', 'date_joined')}),
    )
    
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2'),
        }),
    )
    
    def order_count(self, obj):
        count = obj.order_set.count()
        return format_html('<span style="color: blue;">{}</span>', count)
    order_count.short_description = '订单数'
    
    def user_status(self, obj):
        if obj.is_superuser:
            return format_html('<span style="color: red;">超级管理员</span>')
        elif obj.is_staff:
            return format_html('<span style="color: green;">管理员</span>')
        elif obj.is_active:
            return format_html('<span style="color: blue;">普通用户</span>')
        return format_html('<span style="color: grey;">已禁用</span>')
    user_status.short_description = '用户状态'
    
    actions = ['activate_users', 'deactivate_users']
    
    def activate_users(self, request, queryset):
        updated = queryset.update(is_active=True)
        self.message_user(request, f'成功激活 {updated} 个用户')
    activate_users.short_description = '激活所选用户'
    
    def deactivate_users(self, request, queryset):
        updated = queryset.update(is_active=False)
        self.message_user(request, f'成功禁用 {updated} 个用户')
    deactivate_users.short_description = '禁用所选用户'

# 取消注册默认的 User 管理界面，并注册我们的自定义管理界面
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
